<?php

namespace Biz\service\esSearch;

use Doraemon\service\esSearch\Common;
use Doraemon\tools\Log;

class StoreBasic
{
    public static function syncSave($data)
    {
        Log::position_info('storeEs', 'hello');
        if (isset($data["data"]["id"])) {
            if ($data["type"] == Common::TYPE_ADD) {
                self::saveData($data["data"]);
            } else if ($data["type"] == Common::TYPE_UPDATE) {
                self::saveData($data["data"]);
            }
        }
    }

    public static function saveData($data)
    {
        $aliasJson = $data["alias"];
        $aliasStr = "";

        if ($aliasJson) {
            $aliasArr = json_decode($aliasJson, true);
            $aliasArrFilter = array_filter($aliasArr);

            if (is_array($aliasArrFilter) && $aliasArrFilter) {
                $aliasStr = implode(" ", $aliasArrFilter);
            }
        }

        $formatData = array(
            "id" => $data["id"],
            "uid" => $data["uid"],
            "name" => $data["name"],
            "account_id" => $data["account_id"],
            "alias" => $aliasStr,
            "desc" => $data["desc"],
            "store_status" => $data["store_status"],
        );

        $formatData["updated_time"] = 0;
        $formatData["created_time"] = 0;

        $addTime = $data["addtime"] !== "0000-00-00 00:00:00" ? $data["addtime"] : 0;
        $editTime = $data["edittime"] !== "0000-00-00 00:00:00" ? $data["edittime"] : 0;

        if ($addTime) {
            $formatData["addtime"] = strtotime($addTime);
        }

        if ($editTime) {
            $formatData["edittime"] = strtotime($editTime);
        }

        \Doraemon\service\es\EsStoreBasic::post($data["id"], $formatData);
    }

    public static function saveDataById($storeId)
    {
        $storeInfo = \Biz\model\store\StoreBasic::getInfo($storeId);
        self::saveData($storeInfo);
    }
}